package com.songtai.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.songtai.dao.MessageDao;
import com.songtai.po.Message;
import com.songtai.util.Pager;

/**
 * @author 赵中杨
 * @email zhaozhongyang717@gmail.com
 * @date 2010 2010-4-20 下午04:05:12
 */
public class MessageDaoImpl implements MessageDao {
	private SessionFactory sessionFactory;

	@Override
	public int deleteMessage(String mid) {
		return sessionFactory.getCurrentSession().createQuery("delete from Message m where m.id=:id").setString("id", mid).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<Message> getAllMessage(int currentPage, int pageSize) {
		Session sesion = this.sessionFactory.getCurrentSession();
		int totalCount = sesion.createQuery("from Message").list().size();
		int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;
		List<Message> list = sesion.createQuery("from Message").setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
		Pager<Message> pager = new Pager<Message>(list, currentPage, totalCount, pageCount);
		return pager;
	}

	@Override
	public void addMessage(Message message) {
		this.sessionFactory.getCurrentSession().persist(message);
	}

	/**
	 * @return the sessionFactory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * @param sessionFactory
	 *            the sessionFactory to set
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
